<?php
/**
 * Created by PhpStorm.
 * User: 董坤鸿
 * Date: 2017/1/10
 * Time: 下午3:57
 */

namespace EWeiLink\JuPai\Http\Controllers;

use EWeiLink\JuPai\JpControllerTrait;
use EWeiLink\JuPai\Planner;
use EWeiLink\JuPai\Services\MessageService;
use Illuminate\Http\Request;

class MessagesController
{
    use JpControllerTrait;

    public function index()
    {
        return [];
    }

    /**
     * 发送消息
     */
    public function store()
    {
        return $this->sendMessages();
    }

    public function create()
    {

    }

    public function edit()
    {

    }

    public function update()
    {

    }

    public function destroy()
    {

    }


    /**
     * 监听消息
     */
    public function listenMessages(){
        $time = request('time', 0);    //读取消息的时间
        // 当前登录账户
        $user = request()->user();
        // 根据当前登录账户找到对应的理财师
        $planner = Planner::findByUser($user)->first();
        if ($planner) {
            $message = new MessageService();
            $results = $message->listen($planner->plannerId, $time);
            return $results;
        }
        return $this->_error('理财师不存在');
    }

    /**
     * 发送消息
     * @return array|string
     */
    protected function sendMessages()
    {
        $content = request('content', '');
        $to = request('to', '');
        $type = request('type', 'text_msg');
        if (strlen(trim($content)) <= 0 || empty($to)) {
            return $this->_error('发送失败');
        }
        // 当前登录账户
        $user = request()->user();
        // 根据当前登录账户找到对应的理财师
        $planner = Planner::findByUser($user)->first();
        if($planner){
            $message = new MessageService();
            $results = $message->send($planner->plannerId, $content, $to, $type);
            if ($results) {
                return '';
            }
            $this->_error('发送失败');
        }
        return $this->_error('发送失败');
    }

}